import { createqr, getqrkey, checkqr } from "@/request/api";

export default {
    namespaced: true,
    state: () => ({
        base64: "",
        unikey: "",
        qrcodeIntervalId: null
    }),
    getters: {
    },
    mutations: {
        BASE64(state, base64) {
            state.base64 = base64
        },
        UNIKEY(state, unikey) {
            state.unikey = unikey
        },
        SET_QRCODE_INTERVAL_ID(state, intervalId) {
            state.qrcodeIntervalId = intervalId
        }
    },
    actions: {
        async getqrkey({ commit, dispatch }) {
            let { data } = await getqrkey()
            if (data.code == 200) {
                commit('UNIKEY', data.data.unikey)
                let result = await createqr(data.data.unikey)
                if (result.data.code == 200) {
                    commit('BASE64', result.data.data.qrimg)
                    const intervalId = setInterval(() => {
                        dispatch('checkqrcode', data.data.unikey)
                    }, 1000) 
                    commit('SET_QRCODE_INTERVAL_ID', intervalId)
                }
            }
        },
        async checkqrcode(context, unikey) {
            const { state, commit } = context
            let result = await checkqr(unikey)
            console.log(result);
            if (result.status == 200) {
                if (result.data.code === 803) {
                    const intervalId = state.qrcodeIntervalId
                    if (intervalId) {
                        clearInterval(intervalId)
                        commit('SET_QRCODE_INTERVAL_ID', null)
                    }
                }
            }
        }
    },
}